/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.jowell.common.utils;

import org.apache.http.HttpStatus;

import java.util.HashMap;
import java.util.Map;

/**
 * 返回数据
 *
 * @author Mark sunlightcs@gmail.com
 */
public class Result<T> extends HashMap<String, Object> {
	private static final long serialVersionUID = 1L;

	public static final Integer OK=200;
	public static final Integer ERROR=-1;

	private String message;
	private int retCode;
	private T data;


	private Result(T data) {
		this.retCode = 200;
		this.message = "成功";
		this.data = data;
	}

	public Result(CodeMsg cm) {
		if(cm == null){
			return;
		}
		this.retCode = cm.getRetCode();
		this.message = cm.getMessage();
	}


	public Result(String message) {
		if(message == null){
			return;
		}
		this.message = message;
	}

	/**
	 * 成功时候的调用
	 * @return
	 */
	public static <T> Result<T> ok(T data){
		return new Result<T>(data);
	}

	public Result() {
		put("code", OK);
		put("msg", "success");
	}

	public static Result error() {
		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常，请联系管理员");
	}

	public static Result error(String msg) {
		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
	}

	/**
	 * 失败时候的调用
	 * @return
	 */
	public static <T> Result<T> error(CodeMsg cm){
		return new Result<T>(cm);
	}

	public static Result error(int code, String msg) {
		Result r = new Result();
		r.put("code", code);
		r.put("msg", msg);
		return r;
	}

	public static Result ok(String msg) {
		Result r = new Result();
		r.put("msg", msg);
		return r;
	}

	public static Result ok(Map<String, Object> map) {
		Result r = new Result();
		r.putAll(map);
		return r;
	}

	public static Result ok() {
		return new Result();
	}

	public Result put(String key, Object value) {
		super.put(key, value);
		return this;
	}
}
